package com.ywb.ex09.dao.impl;

import com.ywb.ex09.model.PetItem;
import com.ywb.ex09.tools.JDBCUtils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;

public class PetDao {
    public ArrayList<PetItem>  queryAllData(){
        Connection conn=null;
        Statement st=null;
        ResultSet rs=null;
        ArrayList<PetItem> list=new ArrayList<PetItem>();
        try{
            conn= JDBCUtils.getConnection();
            st=conn.createStatement();
            String sql="select * from pet";
            rs=st.executeQuery(sql);
            while(rs.next()){
                PetItem petItem=new PetItem();
                petItem.setId(rs.getString("id"));
                petItem.setPetname(rs.getString("petname"));
                petItem.setPrice(rs.getDouble("price"));
                petItem.setUnit(rs.getString("unit"));
                list.add(petItem);
            }
            return list;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBCUtils.release(rs,st,conn);
        }
        return null;
    }

    public void addPetItem(PetItem petItem){
        Connection conn=null;
        Statement st=null;
        ResultSet rs=null;
        try{
            conn= JDBCUtils.getConnection();
            st=conn.createStatement();
            String sql="insert into pet(id,petname,price,unit) values('"+petItem.getId()+"','"
                    +petItem.getPetname()+"','"+petItem.getPrice()+"','"+petItem.getUnit()+"')";
            int num=st.executeUpdate(sql);
            if(num>0){
                System.out.println("插入数据成功");
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBCUtils.release(rs,st,conn);
        }
    }

    public void delPetItem(String delId){
        Connection conn=null;
        Statement st=null;
        ResultSet rs=null;
        try{
            conn= JDBCUtils.getConnection();
            String sql="delete from pet where id="+delId;

            int num=st.executeUpdate(sql);
            if(num>0){
                System.out.println("删除数据成功");
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBCUtils.release(rs,st,conn);
        }
    }
}

